package com.huitone.smspfm.core.filter;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

import com.huitone.smspfm.logger.ExtLogger;

import com.bin.common.utils.DateTimeUtils;
import com.bin.common.utils.StringUtils;
import com.huitone.smspfm.core.config.AppStaticConfigs;
import com.huitone.smspfm.core.constant.DealResult;
import com.huitone.smspfm.model.SmsEntityForMt;

/**   
* @Title ForbidTimeFilterTask.java 
* @Package com.huitone.smspfm.core.task 
* @Description TODO(用一句话描述该文件做什么) 
* @author ybliang   
* @date 2017年6月18日 上午10:47:11 
* @version V1.0   
*/
public class ForbidTimeFilterTask extends Thread {
	
	private ExtLogger logger = ExtLogger.create(ForbidTimeFilterTask.class);
	
	private String moduleName = "短信禁发时段过滤模块";
	
	//private byte[] moduleNameB = AppStaticConfigs.stringRedisSerializer.serialize(moduleName); 
	
	private List<SmsEntityForMt> entities = null;
	
	private CyclicBarrier barrier = null;
	
	public ForbidTimeFilterTask(List<SmsEntityForMt> entities, CyclicBarrier barrier) {
		this.entities = entities;
		this.barrier = barrier;
	}

	@Override
	public void run() {
		
		if (entities == null) return;
		
		long start = System.currentTimeMillis();
		
		for (SmsEntityForMt entity:entities) {
			
			String srvNode = StringUtils.toString(entity.getSrvNode());
			String serviceCode = StringUtils.toString(entity.getServiceCode());
			
			Set<String> set = new HashSet<>(); // 所有适用的规则
			
			Set<String> set2 = AppStaticConfigs.configForbidTimeMap.get(srvNode + ":" + serviceCode);
			if (set2 != null) {
				set.addAll(set2);
			}
			Set<String> set3 = AppStaticConfigs.configForbidTimeMap.get(srvNode + ":");
			if (set3 != null) {
				set.addAll(set3);
			}
			Set<String> set4 = AppStaticConfigs.configForbidTimeMap.get(":" + serviceCode);
			if (set4 != null) {
				set.addAll(set4);
			}
			Set<String> set5 = AppStaticConfigs.configForbidTimeMap.get(":");
			if (set5 != null) {
				set.addAll(set5);
			}
			
			Long forbidTimeEnd = null;
			
			for (String str:set) {
				
				if (StringUtils.isEmpty(str)) continue;
				
				String[] strings = str.split(":");
				
				float startTime = StringUtils.strToFlaot(StringUtils.toString(strings[2]));
				
				float endTime = StringUtils.strToFlaot(StringUtils.toString(strings[3]));
				
				if (DateTimeUtils.isInInterval(startTime, endTime)) {
					// 时
					int h = (int) Math.floor(endTime);
					int seconds = (int) Math.floor(new BigDecimal(endTime + "").subtract(new BigDecimal(h + "")).floatValue() * 3600);
					// 分
					int m = (int) Math.floor(seconds / 60);
					// 秒
					int s = seconds - m * 60;
					
					Date currDate = new Date();
					
					String ymd = DateTimeUtils.dateToStr(currDate, "yyyy-MM-dd");
					
					Date date = DateTimeUtils.strToDate(ymd + " " + h + ":" + m + ":" + s, "yyyy-MM-dd HH:mm:ss");
					
					if (startTime < endTime) { // 两个都是今天的时间
						
						forbidTimeEnd = date.getTime();
						
					} else { // startTime是今天的时间, endTime是明天的时间
						
						Integer currentM = StringUtils.strToInteger(DateTimeUtils.dateToStr(currDate, "mm"));
						
						Integer currentH = StringUtils.strToInteger(DateTimeUtils.dateToStr(currDate, "HH"));
						
						float currentTime = currentH + currentM / 60f;
						
						if (currentTime >= 0 && currentTime < endTime) {
							
							forbidTimeEnd = date.getTime();
							
						} else if (currentTime >= startTime && currentTime < 24) {
							
							Calendar calendar = new GregorianCalendar();
							
							calendar.setTime(date);
							
							calendar.add(Calendar.DATE, 1);
							
							forbidTimeEnd = calendar.getTime().getTime();
						}
					}
					
					break;
				}
			}
			
			if (forbidTimeEnd != null) { // 写入SMForbidTList集合
				
				entity.setDealResultCodeMap(moduleName, DealResult.RESULT_1);
				entity.setForbidTimeEnd(forbidTimeEnd);
				entity.setIsforbidsms(true);
				
				logger.debug("[序列号:用户号码][" + entity.getSerialno() + ":" + entity.getPhoneNumber() + "]被禁发时段检测过滤器捕获,短信序列被保存到禁发时段列表,处理流程结束。");
		    	
			} else {
				
				entity.setDealResultCodeMap(moduleName, DealResult.RESULT0);
			}
		}
		
		long end = System.currentTimeMillis();
		
		logger.debug("禁发时段过滤执行完毕,共耗时:" + (end - start) + "毫秒");
		
		try {
			barrier.await();
		} catch (InterruptedException | BrokenBarrierException e) {
			e.printStackTrace();
		}
	}
}
